package com.open.cloud.log.util;

import cn.hutool.http.server.HttpServerRequest;
import com.open.cloud.log.constant.TraceConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.slf4j.MDC;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

/**
 *  @author owen api 经过filter--> interceptor -->aop -->controller 如果某些接口，比如filter
 *         --> userdetail 这种情况，aop mdc设置 后续log输出traceid
 * @author kong
 * @date 2021/4/30
 * blog: http://blog.kongyin.ltd
 */
public class TraceUtil {

    public static String getTrace() {
        HttpServerRequest request = (HttpServerRequest) ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
        String appTraceId = request.getHeader(TraceConstant.HTTP_HEADER_TRACE_ID);
        // 未经过HandlerInterceptor的设置
        if (StringUtils.isBlank(MDC.get(TraceConstant.LOG_TRACE_ID))) {
            // 但是有请求头，重新设置
            if (StringUtils.isNotEmpty(appTraceId)) {
                MDC.put(TraceConstant.LOG_TRACE_ID, appTraceId);
            }
        }
        return appTraceId;
    }
}
